import {
    Dispatch
} from 'redux';

import {
    Tip
} from './../../components';

import {
    MessageItem
} from './../../components/ImUi/types';

import ajax from './../../http';
import * as types from './../types/chat';
import getUserId from './../../utils/userId';

interface Payload {
    limit?: number,
    isPush?: boolean,
    lastId?: number
}

interface HistoryPayload extends Payload {
    chatRoomId: string,
    curFirstChatId?: number | string
}

interface afterHistoryPayload {
    chatRoomId: string,
    curLastChatId: number | string
}

interface SendMessagePayload extends MessageItem {
    userId?: number | string
}

interface AppendPayload extends MessageItem {
    messages: Array<MessageItem>
}

interface UpdateUnreadPayload {
    number:number,
    chatRoomId:string
}

export default {
    //获取聊天列表
    [types.getUserMessageList](
        payload: Payload
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    lastId,
                    isPush,
                    limit = 300
                } = payload;
                const _para = {
                    limit,
                    lastId
                }
                const list = (
                    await ajax.get(
                        `chatted/users`,
                        _para
                    )
                )
                const _data = {
                    isPush: isPush,
                    queryList: list,
                    userId: getUserId()
                }
                dispatch({
                    data: _data,
                    type: types.getUserMessageList
                })
                return list;
            }
            catch (e) {
                return Promise.reject(e)
            }
        }
    },
    //删除某条消息记录
    [types.deleteMessageRow](toUserId:string|number) {
        return async ( dispatch: Dispatch) => {
            try {
                await ajax.delete(`chat/user`,{
                    toUserId:toUserId
                })
                dispatch({
                    data:{
                        toUserId:toUserId,
                        userId: getUserId()
                    },
                    type:types.deleteMessageRow
                })
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //更新聊天列表
    [types.updateMessageList](
        payload: AppendPayload
    ) {
        return async (
            dispatch: Dispatch,
            getState: Function
        ) => {
            const {
                messages
            } = payload;

            const {
                chat
            } = getState();

            const userId = (
                getUserId()
            )

            const {
                lists
            } = chat;

            const list = (
                lists[userId] || []
            )

            const update = messages.some((_item:any) => (
                !list.find((item: any) => (
                    item.chatRoomId === _item.chatRoomId
                ))
            ))

            //更新列表
            if(update) {
                const _para = {
                    lastId:0,
                    isPush:false
                }
                this[types.getUserMessageList](
                    _para
                )
            }
            else {
                const _data = {
                    userId:userId,
                    messages:messages
                }
                dispatch({
                    data:_data,
                    type:types.updateMessageList
                })
            }
        }
    },
    //获取聊天历史记录
    [types.getHistoryList](
        payload: HistoryPayload
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    limit = 30,
                    chatRoomId,
                    isPush = false,
                    curFirstChatId = 0
                } = payload;
                const _para = {
                    limit,
                    curFirstChatId
                }
                const _url = (
                    `sv2/chatroom/${chatRoomId}/history`
                )
                const list = (
                    await ajax.get(_url, _para)
                )
                const _data = {
                    isPush: isPush,
                    queryList: list,
                    chatRoomId: chatRoomId
                }
                dispatch({
                    data: _data,
                    type: types.getHistoryList
                })
                return list;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //获取某条消息之后的消息
    [types.getMessageAfterList](
        payload: afterHistoryPayload
    ) {
        return async (dispatch: Dispatch) => {
            try {
                const {
                    chatRoomId,
                    curLastChatId
                } = payload;
                const _para = {
                    limit: 200,
                    curLastChatId: curLastChatId
                }
                const _url = (
                    `sv2/chatroom/${chatRoomId}/history`
                )
                const list = (
                    await ajax.get(_url, _para)
                )
                const _data = {
                    queryList: list,
                    chatRoomId: chatRoomId
                }
                dispatch({
                    data: _data,
                    type: types.getMessageAfterList
                })
                return list;
            }
            catch (e) {
                return Promise.reject(e);
            }
        }
    },
    //追加消息
    [types.appendMessageList](
        payload: AppendPayload
    ) {
        return {
            data: payload,
            type: types.appendMessageList
        }
    },
    //更新消息
    [types.updateMessageItem](payload: MessageItem) {
        return {
            data: payload,
            type: types.updateMessageItem
        }
    },
    //删除消息
    [types.deleteMessageItem](payload: MessageItem) {
        return {
            data: payload,
            type: types.deleteMessageItem
        }
    },
    //发送消息
    [types.sendMessage](payload: SendMessagePayload) {
        return async (dispatch: Dispatch) => {
            try {
                let {
                    text,
                    msgId,
                    userId,
                    msgType,
                    extend,
                    mediaPath,
                    chatRoomId,
                    isReSending
                } = payload as any;
                //如果是重发先删除
                if (isReSending) {
                    this[types.deleteMessageItem](
                        payload
                    )
                }
                //先把历史记录存一下
                this[types.appendMessageList]({
                    messages: [payload]
                } as any)
                this[types.updateMessageList]({
                    messages:[payload]
                } as any)
                //如果是图片，先上传图片
                if (msgType === `image`) {
                    const {
                        url,
                        width,
                        height
                    } = await (
                        ajax.uploadImage(mediaPath)
                    ) as any;
                    const queryStr = (
                        `w=${width}&h=${height}`
                    )
                    const _extend = {
                        duration: 0,
                        mediaId: msgId,
                        mediaPath: `${url}?${queryStr}`,
                    }
                    extend = (
                        JSON.stringify(_extend)
                    )
                }
                const _Para = {
                    photoId: 0,
                    message: text,
                    type: msgType,
                    extend: extend,
                    chatRoomId: chatRoomId
                }
                const {
                    status,
                    chatHistoryId
                } = await ajax.post(
                    `chat/${userId}`,
                    _Para
                ) as any;
                const _update = {
                    ...payload,
                    status: status,
                    chatHistoryId: chatHistoryId
                }
                this[types.updateMessageItem](
                    _update
                )
                return _update;
            }
            catch (e) {
                const _update = {
                    ...payload,
                    status: `send_failed`
                }
                this[types.updateMessageItem](
                    _update as any
                )
                Tip.warm({
                    message:e.message
                })
                return _update;
            }
        }
    },
    //更新小红点
    [types.updateMessageUnread](
        payload:UpdateUnreadPayload
    ) {
        return {
            data:payload,
            type:types.updateMessageUnread
        }
    },
    //清空
    [types.clearMessageUnread](chatRoomId:string) {
        return {
            data:chatRoomId,
            type:types.clearMessageUnread
        }
    },
    //清除connection未读信息
    [types.clearConnectionUnRead](
        tab:string,userId:number
    ) {
        return {
            data:{tab, userId},
            type:types.clearConnectionUnRead
        }
    },
    //清除connection某个tab的数据
    [types.clearUnReadForTab](tab:string) {
        return {
            data:tab,
            type:types.clearUnReadForTab
        }
    },
    //服务端获取未读消息
    [types.getServerUnreadMsg](userId:number){
        return async (dispatch:Dispatch) => {
            try {
                const {
                    message,
                    connect,
                } = await ajax.get(
                    `connection/detail/status`
                ) as any;

                const {
                    charRoomIds
                } = message;
                const __keys = (
                    Object.keys(connect)
                )

                const _keys = (
                    Object.keys(charRoomIds)
                )

                if(!!_keys.length) {
                    dispatch({
                        data:charRoomIds,
                        type:types.getServerUnreadMsg,
                    })
                }

                __keys.forEach((key:string) => {
                    const userIds = connect[key] || [];
                    if(userIds.length > 0) {
                        const _data = {
                            value:userIds,
                            key:`${key}_${userId}`
                        }
                        dispatch({
                            data:_data,
                            type:types.getConnectUnread
                        })
                    }
                })
            }
            catch (e) {
                return Promise.reject(e)
            }
        }
    }
}
